package com.curtain.koreyoshi.view.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Handler;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.curtain.koreyoshi.utils.ResUtil;


/**
 * Created by leejunpeng on 2016/4/7.
 */
public class VerticalLock extends LinearLayout {

    private final int RING_ID = 10001;
    private final int POINT_ID = 10002;

    private Context mContext;
    private Bitmap drawBitmap;// 滑动图片
    public RingView topImageView;// 上控件
    private ArrowView bottomImageView;// 下控件
    private LinearLayout pointImageView;
    private UnlockListener unListener;

    public void setUnlockListener(UnlockListener unListener){
        this.unListener = unListener;
    }

    public VerticalLock(Context context) {
        super(context);
        this.mContext = context;
        initView();
        getDrawBitmap();// 初始化滑动图片
        setWillNotDraw(false);// 防止onDraw方法不执行
    }

    private void initView() {
        // TODO Auto-generated method stub
        setOrientation(LinearLayout.VERTICAL);
        setGravity(Gravity.CENTER_HORIZONTAL);
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, ResUtil.heightDip2px(140));
        topImageView = new RingView(mContext);
//        topImageView.setImageResource(R.mipmap.charge_voltage);
//        RingView ringView = new RingView(this);
        topImageView.setInnerRadius(ResUtil.heightDip2px(30));
        topImageView.setRingRadius(ResUtil.heightDip2px(8));
        topImageView.setRingInval(ResUtil.heightDip2px(2));
        topImageView.setArc(true);
        topImageView.setBattery(0.7f);
        topImageView.setId(RING_ID);
        this.addView(topImageView,params);

        LayoutParams params2 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        params2.topMargin = ResUtil.heightDip2px(20);
        params2.bottomMargin = ResUtil.heightDip2px(28);
        pointImageView = new LinearLayout(mContext);
        pointImageView.setOrientation(LinearLayout.VERTICAL);
//        pointImageView.setImageResource(R.mipmap.charge_circle);
        LayoutParams pointParams = new LayoutParams(LayoutParams.MATCH_PARENT, ResUtil.heightDip2px(20));
        pointParams.topMargin = ResUtil.heightDip2px(8);
        for(int i=0;i<5;i++) {
            PointView pointView = new PointView(mContext);
            pointView.setRingRadius(ResUtil.heightDip2px(10));
            pointImageView.addView(pointView,pointParams);
        }
        pointImageView.setId(POINT_ID);
        this.addView(pointImageView,params2);

        LayoutParams params3 = new LayoutParams(ResUtil.widthDip2px(76),ResUtil.heightDip2px(84));
        bottomImageView = new ArrowView(mContext);
        bottomImageView.setWidth(ResUtil.widthDip2px(76));
        bottomImageView.setHeight(ResUtil.heightDip2px(84));
//        bottomImageView.setImageResource(R.mipmap.charge_unlock);
        this.addView(bottomImageView,params3);

    }

    private void getDrawBitmap() {
        // TODO Auto-generated method stub
        if (drawBitmap == null) {
            drawBitmap = Bitmap.createBitmap(ResUtil.widthDip2px(76), ResUtil.heightDip2px(84), Bitmap.Config.ARGB_4444);
            Canvas canvas = new Canvas(drawBitmap);
            bottomImageView.draw(canvas);
//            drawBitmap = BitmapFactory.decodeResource(mContext.getResources(),
//                    R.mipmap.charge_unlock);
        }
    }

    private int locationY;// 点击位置
    private Handler mHandler = new Handler();

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                System.out.println("action_down");
                locationY = y;
                return isActionDown(event);

            case MotionEvent.ACTION_MOVE:
                System.out.println("action_move");
                if (Math.abs(y - locationY) <= 20){
                    return true;
                }
                locationY = y;
                if (locationY > drawYMax) {
                    return true;
                }
                invalidate();
                return true;
            case MotionEvent.ACTION_UP:
                System.out.println("action_up");
                if (!isLocked()) {
                    if (unListener != null ) {
                        unListener.unlockFailure();
                    }
                    imageBack(event);
                }else {
                    if(unListener != null ){
                        unListener.unlockSuccess();
                    }
                }
                return true;
        }

        return super.onTouchEvent(event);
    }

    private static final int MOVE_TIME = 10;// 移动时间
    private static final float MOVE_SPEED = 0.9f;// 移动速度

    /**
     * 滑动图片回退
     *
     * @param event
     */
    private void imageBack(MotionEvent event) {
        locationY = (int) (event.getY());
        if (locationY < drawYMax) {
            mHandler.postDelayed(runnableImgBack, MOVE_TIME);
        }

    }

    /**
     * 回退线程变量
     */
    private Runnable runnableImgBack = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub

            if (locationY < drawYMax) {
                if(locationY + MOVE_SPEED * MOVE_TIME > drawYMax){
                    locationY = drawYMax;
                }
                mHandler.postDelayed(runnableImgBack, MOVE_TIME);
                invalidate();
            } else {
                bottomImageView.setVisibility(View.VISIBLE);
                clearVariable();
            }
            locationY = locationY + (int) (MOVE_SPEED * MOVE_TIME);
        }
    };

    int temp = 0;// 全局变量，用来储存触摸点位置与滑动图片宽度的差
    //	int tempCount = 0;// 全局变量
    int mDrawY = 0;// 全局变量，储存每次绘画的y坐标

    /**
     * 清除变量
     */
    private void clearVariable() {

        temp = 0;
//		tempCount = 0;
        mDrawY = 0;

    }

    /**
     * 判断是否点击到了滑动图片
     *
     * @param event
     * @return
     */
    private boolean isActionDown(MotionEvent event) {

        Rect rect = new Rect();
        bottomImageView.getHitRect(rect);
        boolean isDown = rect.contains((int) event.getX(), (int) event.getY());
        if (isDown) {
            bottomImageView.setVisibility(View.GONE);
        }
        System.out.println("idDown==" + isDown);
        return isDown;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        drawImage(canvas);
    }

    private int drawYMax;// 滑动图片能滑动的Y坐标的最大值
    private int drawYmin;// 滑动图片能滑动的Y坐标的最小值

    private void drawImage(Canvas canvas) {
        // 得到最大值
        drawYMax = bottomImageView.getTop();
        drawYmin = topImageView.getTop();
        // 设置绘制图片的Y坐标
        int drawY = locationY;
        // 设置绘制图片的X坐标
        int drawX = (getScreenWidth() - bottomImageView.getWidth()) / 2;
        // 如果点击位置大于滑动图片的y坐标值
        if (locationY > drawYMax) {
            locationY = drawYMax;
            bottomImageView.setVisibility(View.VISIBLE);
            return;
        }

        if(drawY >= temp){
            drawY = drawYMax;
        }
        // 判断绘制图片的X坐标是否到了最大值
        if (drawY > drawYMax) {
            drawY = drawYMax;
        }

        if(drawY < drawYmin){
            drawY = drawYmin;
        }
        // 把绘制图片的y坐标取出来，用来判断是否解锁成功
        mDrawY = drawY;
        if(drawYMax - locationY <= MOVE_SPEED * MOVE_TIME){
            locationY = drawYMax;
        }
        bottomImageView.setVisibility(View.GONE);
        if (locationY == drawYMax) {
            bottomImageView.setVisibility(View.VISIBLE);
            return;
        }
        canvas.drawBitmap(drawBitmap, drawX, drawY > drawYMax ? drawYMax : drawY,
                null);
        // 得到点击位置与绘制图片的差
        temp = locationY;

    }

    /**
     * @return 是否已经成功解锁
     */
    private boolean isLocked() {
        if (mDrawY > 0 && mDrawY <= (drawYmin + topImageView.getHeight()/2)) {
            return true;
        }
        return false;

    }

    /**
     * @return 屏幕高度
     */
    private int getScreenHeight() {
        int h = ((WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getHeight();
        return h;
    }

    /**
     * @return 屏幕宽度
     */
    private int getScreenWidth() {
        int w = ((WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getWidth();
        return w;
    }

    public interface UnlockListener{
        void unlockSuccess();
        void unlockFailure();
    }
}
